const { createCipheriv, createDecipheriv } = require('crypto');

// openssl list -cipher-algorithms 命令支持的算法
const algorithms = {
  ecb: 'des-ecb',
  cbc: 'des-cbc',
};

class DES {
  /**
   * DES 类
   * @param {string} algorithm 算法模式 'ecb' 'cbc'
   * @param {string} key 密钥 长度为8
   * @param {string} iv 偏移量 cbc模式需要 长度为8
   */
  constructor(mode, key, iv) {
    this.algorithm = algorithms[mode];
    this.key = key;
    this.iv = iv || null;
  }
  encrypt(plaintext) {
    const cipher = createCipheriv(this.algorithm, this.key, this.iv);
    cipher.setAutoPadding(true); //default true
    let ciphtext = cipher.update(plaintext, 'utf8', 'hex');
    ciphtext += cipher.final('hex');
    return ciphtext;
  }
  decrypt(ciphtext) {
    const decipher = createDecipheriv(this.algorithm, this.key, this.iv);
    decipher.setAutoPadding(true);
    let txt = decipher.update(ciphtext, 'hex', 'utf8');
    txt += decipher.final('utf8');
    return txt;
  }
}

module.exports = DES;
